package com.custom.access.echat.handler.facebook.messenger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.custom.access.center.MsgHandleContext;
import com.custom.access.constant.CommonConstantPool;
import com.custom.access.constant.CustomMsgType;
import com.custom.access.echat.constant.EchatConstantPool;
import com.custom.access.facebook.constant.FacebookConstantPool;
import com.custom.access.facebook.messenger.info.*;
import com.custom.access.info.MediaChatConfig;
import com.custom.access.msg.CustomNewsMsg;
import com.custom.access.msg.extend.NewsInfo;
import com.custom.access.scanner.annotation.MsgHandler;
import com.custom.access.util.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author huangzhilin
 * @Date 2020/2/27
 */
@Slf4j
@MsgHandler(msgType = CustomMsgType.MsgTypeDefine.news, mediaType = CommonConstantPool.CommonCustomMediaDefine.facebook)
public class NewsMsgHandler extends AbstractFacebookMsgHandler<CustomNewsMsg> {

    /**
     * 使用把图文消息当文本消息处理的公司id列表
     */
    private final static List<Long> useTextCompanyIdList = Arrays.asList(531938L,521863L, 522116L, 522115L, 525942L, 521442L, 100L, 602L, 523490L,529440L,524127L,529408L);

    /**
     * @param customNewsMsg
     * @return
     */
    @Override
    protected List<Object> buildMessage(MsgHandleContext context, CustomNewsMsg customNewsMsg) {
        NewsInfo newsInfo = customNewsMsg.getNews();
        if (newsInfo == null) {
            return null;
        }
        if (customNewsMsg.getChatType() != null
                && (EchatConstantPool.ChatInfoTypeDefine.offline == customNewsMsg.getChatType()
                || EchatConstantPool.ChatInfoTypeDefine.leave == customNewsMsg.getChatType())
                && context.getCompanyId() != null && useTextTypeToSendMsg(context)) {
            //指定公司留言图文消息使用文本格式
            log.error("NewsMsgHandler buildMessage.news:{}", JSON.toJSONString(customNewsMsg));
            return Arrays.asList(new MessageInfo(HtmlUtil.html2TextFacebook(getNewsContent(customNewsMsg.getChatType(), newsInfo))));
        }
        //创建element，并且绑定action
        ElementInfo elementInfo = new ElementInfo();
        elementInfo.setTitle(newsInfo.getTitle());
        if (customNewsMsg.getChatType() != null
                && (EchatConstantPool.ChatInfoTypeDefine.offline == customNewsMsg.getChatType()
                || EchatConstantPool.ChatInfoTypeDefine.leave == customNewsMsg.getChatType())) {
            String offlineTitle = RedisUtil.getI18nConfig(context.getCompanyId(), CommonConstantPool.I18nConfig.offlineTitle);
            if (StringUtil.isNotEmpty(offlineTitle)) {
                elementInfo.setTitle(offlineTitle);
            }
        }
        if (customNewsMsg.getChatType() != null) {
            String newsContent = getNewsContent(customNewsMsg.getChatType(), newsInfo);
            elementInfo.setSubtitle(newsContent);
            if (StringUtil.isEmpty(elementInfo.getSubtitle())) {
                String offlineDefaultContent = RedisUtil.getI18nConfig(context.getCompanyId(), CommonConstantPool.I18nConfig.offlineDefaultContent);
                elementInfo.setSubtitle(StringUtil.isEmpty(offlineDefaultContent) ? CommonConstantPool.BLANCK_STR : offlineDefaultContent);
            }
        }else if(StringUtil.isNotEmpty(newsInfo.getContent())){
            elementInfo.setSubtitle(newsInfo.getContent());
        }

        if (newsInfo.getImageUrl() != null) {
            elementInfo.setImage_url(newsInfo.getImageUrl());
        }
        if (newsInfo.getUrl() != null) {
            //处理可能的一洽图文链接，如"http('https://m.rainbowred.com','inner')"
            String url = StringUtil.newsInfoUrlIfEchatCustom(newsInfo);
            newsInfo.setUrl(url);
            //带图片和跳转url
            ElementActionInfo action = new ElementActionInfo();
            action.setType(FacebookConstantPool.ElementActionTypDefine.WEB_URL);
            action.setUrl(newsInfo.getUrl());
            elementInfo.setDefault_action(action);
        }
        //组件payload
        PayloadInfo payloadInfo = new PayloadInfo(FacebookConstantPool.TemplageTypeDefine.GENERICE, Arrays.asList(elementInfo));
        //组建attachment
        AttachmentInfo attachment = new AttachmentInfo(FacebookConstantPool.MessageTypeDefine.TEMPLATE, payloadInfo);
        return Arrays.asList(new MessageInfo(attachment));
    }


    /**
     * @param context
     * @return 当前渠道是否使用文本类型发送留言回复
     */
    private boolean useTextTypeToSendMsg(MsgHandleContext context) {
        boolean useText =  useTextCompanyIdList.contains(context.getCompanyId());
        if (!useText) {
            MediaChatConfig chatConfig = RedisUtil.getMediaChatConfig(context.getCompanyId(), context.getMediaId());
            if (chatConfig != null && chatConfig.getPushMsgType() == CommonConstantPool.PushMsgSendType.textType) {
                useText = true;
            }
        }
        return useText;
    }

    /**
     * @param news
     * @return
     */
    private String getNewsContent(byte type, NewsInfo news) {
        try {
            String decodeUrl = URLUtil.decode(news.getUrl());
            /**
             * http://www.echatsoft.com/visitor/common/record.html?url=xxx
             */
            String[] splitArray = decodeUrl.split("\\?url=");
            if (splitArray == null || splitArray.length < 2) {
                return null;
            }
            /**
             * http%3A%2F%2Feapi.echatsoft.com%2Fpaodm%2Fqd%3FcompanyId%3D531521%26visitorId%3DcustomxR6hbF5k8617301993532%26chatInfoType%3D4%26talkId%3D114170%26tm%3D1720767525752%26token%3DC87451A167DB7CE490D635594ACDA7ED
             */
            String url = splitArray[1];

            String content = null;
            if (type == EchatConstantPool.ChatInfoTypeDefine.leave) {
                //推送
                int retry = 1;
                do {
                    if (retry++ >= 3) {
                        log.error("查询推送超过重试次数，跳出");
                        break;
                    }
                    String resp = HttpUtil.getWithNotProxy(url);
                    if (resp.equals("0")) {
                        log.error("查询推送没有查到记录准备睡眠2s");
                        Thread.sleep(2000L);
                        continue;
                    }
                    /**
                     * {
                     *   "extImg": "https://vfile.rainbowred.com/group1/M00/A8/EB/wKhCBGKpz32AeGpiAAATLAuWCkU900.jpg",
                     *  " pushInfo": {
                     *     "companyId": 531521,
                     *     "content": "{\"bin\":28,\"binDefine\":28,\"brief\":\"怎么说 [图片]https://qnfile.echatsoft.com/09d158ac-6b9b\",\"chatInfoType\":4,\"companyId\":531521,\"content\":\"<p>怎么说 <img class=\\\"chat-editor-image\\\" name=\\\"AMG-GTR.png\\\" title=\\\"点击查看原图\\\" src=\\\"https://qnfile.echatsoft.com/09d158ac-6b9b-493d-9a4a-a5904a25f175\\\"><\\/p><p><span class=\\\"ql-cursor\\\">﻿<\\/span><\\/p>\",\"id\":0,\"lan\":\"zh\",\"media\":9,\"mid\":689915,\"mst\":2,\"mt\":\"655\",\"newsMsgId\":\"114238\",\"pushMedias\":\"9\",\"rph\":0,\"sendMsgToKafka\":true,\"sendStatus\":1,\"signature\":\"E11EF332385EA29FDA41FE6BF6B12118\",\"staffId\":16559,\"staffName\":\"彭玮标\",\"staffNickName\":\"彭玮标\",\"talkId\":\"114238\",\"talkType\":4,\"tm\":1720774245625,\"vcs\":1,\"visitorId\":\"customxR6hbF5k8617301993532\"}",
                     *     "contentType": 10,
                     *     "eventTime": 1720774245625,
                     *     "eventType": 1,
                     *     "id": 114238,
                     *     "staffId": 16559,
                     *     "vipid": "xR6hbF5k8617301993532",
                     *     "viptype": 5
                     *   }
                     * }
                     */
                    JSONObject jsonObject = JSON.parseObject(resp);
                    JSONObject pushInfo = jsonObject.getJSONObject("pushInfo");
                    if (pushInfo != null) {
                        /**
                         * {
                         *     "companyId": 531521,
                         *     "content": "{\"bin\":28,\"binDefine\":28,\"brief\":\"怎么说 [图片]https://qnfile.echatsoft.com/09d158ac-6b9b\",\"chatInfoType\":4,\"companyId\":531521,\"content\":\"<p>怎么说 <img class=\\\"chat-editor-image\\\" name=\\\"AMG-GTR.png\\\" title=\\\"点击查看原图\\\" src=\\\"https://qnfile.echatsoft.com/09d158ac-6b9b-493d-9a4a-a5904a25f175\\\"><\\/p><p><span class=\\\"ql-cursor\\\">﻿<\\/span><\\/p>\",\"id\":0,\"lan\":\"zh\",\"media\":9,\"mid\":689915,\"mst\":2,\"mt\":\"655\",\"newsMsgId\":\"114238\",\"pushMedias\":\"9\",\"rph\":0,\"sendMsgToKafka\":true,\"sendStatus\":1,\"signature\":\"E11EF332385EA29FDA41FE6BF6B12118\",\"staffId\":16559,\"staffName\":\"彭玮标\",\"staffNickName\":\"彭玮标\",\"talkId\":\"114238\",\"talkType\":4,\"tm\":1720774245625,\"vcs\":1,\"visitorId\":\"customxR6hbF5k8617301993532\"}",
                         *     "contentType": 10,
                         *     "eventTime": 1720774245625,
                         *     "eventType": 1,
                         *     "id": 114238,
                         *     "staffId": 16559,
                         *     "vipid": "xR6hbF5k8617301993532",
                         *     "viptype": 5
                         *   }
                         */
                        String contentWrapper = pushInfo.getString("content");
                        /**
                         * "content": "{\"bin\":28,\"binDefine\":28,\"brief\":\"怎么说 [图片]https://qnfile.echatsoft.com/09d158ac-6b9b\",\"chatInfoType\":4,\"companyId\":531521,\"content\":\"<p>怎么说 <img class=\\\"chat-editor-image\\\" name=\\\"AMG-GTR.png\\\" title=\\\"点击查看原图\\\" src=\\\"https://qnfile.echatsoft.com/09d158ac-6b9b-493d-9a4a-a5904a25f175\\\"><\\/p><p><span class=\\\"ql-cursor\\\">﻿<\\/span><\\/p>\",\"id\":0,\"lan\":\"zh\",\"media\":9,\"mid\":689915,\"mst\":2,\"mt\":\"655\",\"newsMsgId\":\"114238\",\"pushMedias\":\"9\",\"rph\":0,\"sendMsgToKafka\":true,\"sendStatus\":1,\"signature\":\"E11EF332385EA29FDA41FE6BF6B12118\",\"staffId\":16559,\"staffName\":\"彭玮标\",\"staffNickName\":\"彭玮标\",\"talkId\":\"114238\",\"talkType\":4,\"tm\":1720774245625,\"vcs\":1,\"visitorId\":\"customxR6hbF5k8617301993532\"}",
                         */
                        if (contentWrapper != null) {
                            /**
                             * {
                             *     "bin": 28,
                             *     "binDefine": 28,
                             *     "brief": "怎么说 [图片]https://qnfile.echatsoft.com/09d158ac-6b9b",
                             *     "chatInfoType": 4,
                             *     "companyId": 531521,
                             *     "content":
                             *     "
                             *         <p>怎么说<img class="chat-editor-image" name="AMG-GTR.png" title="点击查看原图" src="https://qnfile.echatsoft.com/09d158ac-6b9b-493d-9a4a-a5904a25f175">
                             *         </p>
                             *         <p>
                             *             <span class="ql-cursor">﻿</span>
                             *         </p>
                             *     ",
                             *     "id": 0,
                             *     "lan": "zh",
                             *     "media": 9,
                             *     "mid": 689915,
                             *     "mst": 2,
                             *     "mt": "655",
                             *     "newsMsgId": "114238",
                             *     "pushMedias": "9",
                             *     "rph": 0,
                             *     "sendMsgToKafka": true,
                             *     "sendStatus": 1,
                             *     "signature": "E11EF332385EA29FDA41FE6BF6B12118",
                             *     "staffId": 16559,
                             *     "staffName": "彭玮标",
                             *     "staffNickName": "彭玮标",
                             *     "talkId": "114238",
                             *     "talkType": 4,
                             *     "tm": 1720774245625,
                             *     "vcs": 1,
                             *     "visitorId": "customxR6hbF5k8617301993532"
                             * }
                             */
                            content = JSONObject.parseObject(contentWrapper).getString("translation");
                            if (StringUtil.isEmpty(content)) {
                                content = JSONObject.parseObject(contentWrapper).getString("content");
                            } else {
                                content = content.replace("<p>", "")
                                        .replace("</p>", "");
                            }
                        }
                    }
                    if (content != null) {
                        break;
                    }
                } while (true);
            } else {
                //留言
                int retry = 1;
                do {
                    String resp = HttpUtil.getWithNotProxy(url);
                    JSONObject jsonObject = JSON.parseObject(resp);
                    JSONArray details = jsonObject.getJSONArray("offlineDetailList");
                    if (details != null && details.size() != 0) {
                        for (int i = details.size() - 1; i >= 0; i--) {
                            JSONObject detailJSONObject = JSON.parseObject(details.get(i).toString());
                            if (detailJSONObject.getInteger("eventType") == 1) {
                                content = detailJSONObject.getString("translation");
                                if (StringUtil.isEmpty(content)) {
                                    String contentWrapper = detailJSONObject.getString("content");
                                    if (StringUtil.isNotEmpty(contentWrapper)) {
                                        content = JSONObject.parseObject(contentWrapper).getString("content");
                                    }
                                } else {
                                    content = content.replace("<p>", "")
                                            .replace("</p>", "");
                                }
                                break;
                            }
                        }
                    }
                    if (content != null || retry++ >= 3) {
                        log.error("查询留言跳出.尝试次数：{}", retry - 1);
                        break;
                    }
                    log.error("查询对话没有查到记录准备睡眠2s");
                    Thread.sleep(2000L);
                } while (true);
            }
            if (content == null) {
                log.error("解析content为空，使用news.content。");
                content = news.getContent();
            }
            log.error("getNewsContent返回:{}", content);
            return content;
        } catch (Exception e) {
            log.error("getNewsContent occur Exception。", e);
        }
        return null;
    }

    /**
     * 本地测试方法
     */
    public static void main(String[] args) {
        String str = "[#1f620#][#2f420#]你好[图片]";
        String regex = "\\[#\\w*#\\]";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(str);
        int i = 0;
        Map<String, String> replaceMap = new HashMap<>();
        while (m.find()) {
            // group(0)或group()将会返回整个匹配的字符串（完全匹配）；group(i)则会返回与分组i匹配的字符
            // 这个例子只有一个分组
            System.out.println(m.group(0));
            String origin = m.group(0);
            String newStr = origin.replace("[#", "&#x${").replace("#]", "};");
            replaceMap.put(origin, newStr);
        }
        String returnStr = str;
        for (Map.Entry<String, String> e : replaceMap.entrySet()) {
            returnStr = returnStr.replace(e.getKey(), e.getValue());
        }
        System.err.println(returnStr);
    }
}
